package com.gl.glcourses.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import com.gl.glcourses.repository.dao.IProjectRepository;
import com.gl.glcourses.vos.Oficina;

public abstract class JpaProjectRepository<EntityType> implements IProjectRepository<EntityType> {

	@PersistenceContext
	protected EntityManager em;
	
	@Override
	public EntityType find(Class clase, String atributo, String parametro) {
		
		EntityType entity;
		try {

			Query query = em.createQuery("FROM " + clase.getSimpleName()
					+ " as objeto WHERE objeto." + atributo + " = :param");
			query.setParameter("param", parametro);
			return entity = (EntityType) query.getSingleResult();

		} catch (Exception e) {
			return null;
		}
	}
	
	
	@Override
	public EntityType saveAndReturn(EntityType entity) throws Exception {
		EntityType persist = null;
		try {
			persist = em.merge(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return persist;
	}

	@Override
	public void save(EntityType entity) throws Exception {
		try { 
			em.persist(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
	}

	@Override
	public EntityType saveUpdateAndReturn(EntityType entity) throws Exception {
		EntityType merge = null;
		try {
			merge = em.merge(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		System.out.println(merge);
		return merge;
	}

	@Override
	public void saveUpdate(EntityType entity) throws Exception {
		try {
			em.merge(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
	}

	@Override
	public EntityType findById(Long id, Class clase) throws Exception {
		EntityType entity;
		try {
			 entity= (EntityType) em.find(clase, id);	
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return entity;
	}

	@Override
	public void delete(EntityType entity) throws Exception {
		try {
			em.remove(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}	
	}

	@Override
	public List<EntityType> getListEntity(Class clase) throws Exception {
		Query query = null;
		try {
			query = em.createQuery("FROM " + clase.getSimpleName());
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
		return query.getResultList();
	}

}
